package com.mofum.msdom.excel.hander.poi;

import com.mofum.msdom.excel.annotation.parser.impl.ATColumnParser;
import com.mofum.msdom.excel.annotation.parser.impl.ATSheetParser;
import com.mofum.msdom.excel.annotation.parser.impl.ATStyleParser;
import com.mofum.msdom.excel.annotation.parser.impl.ATWorkbookParser;
import com.mofum.msdom.excel.converter.TypeConverter;
import com.mofum.msdom.excel.metadata.MPColumn;
import com.mofum.msdom.excel.metadata.MPSheet;
import com.mofum.msdom.excel.metadata.MPWorkbook;
import com.mofum.msdom.excel.parser.ExcelParserCallback;
import com.mofum.msdom.excel.validator.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * 表格内容 注解解析器
 *
 * @author 1615690513@qq.com
 * @since 2018/11/21 0021 18:14
 */
public class AnnotationContentHandler<T, P extends ExcelParserCallback<T>> extends TypeContentHandler<T, P> {

    public static Logger logger = LoggerFactory.getLogger(AnnotationContentHandler.class);

    public AnnotationContentHandler() {
    }

    public AnnotationContentHandler(Class<T> dataType, P callback) {

        try {
            //创建解析器
            ATColumnParser<Object> columnParser = new ATColumnParser<>();

            //解析出列
            Map<Field, MPColumn> columnMap = columnParser.parseField(dataType);

            //设置列Map
            this.setColumnMap(columnMap);

            //转换成索引Map
            Map<Integer, String> indexMap = columnMapToIndexMap(columnMap);

            //设置索引Map
            this.setIndexMap(indexMap);

            Map<Field, TypeConverter> converterMap = columnMapToConverterMap(columnMap, getExcelConfig().getConverter());

            this.setConverterMap(converterMap);

            Map<Field, Validator> validatorMap = columnMapTValidatorMap(columnMap);

            this.setValidatorMap(validatorMap);

            ATWorkbookParser<Object> atWorkbookParser = new ATWorkbookParser<Object>();

            Map<Type, MPWorkbook> mpWorkbookMap = atWorkbookParser.parseType(dataType);

            MPSheet[] sheets = mpWorkbookMap.get(dataType).getSheets();

            this.setSheets(sheets);

            this.setDataFilterMap(sheetMapToDataFilterMap(sheetArrayToDataFilterMap(sheets)));


        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }

        //设置解析数据的类型
        this.setDataType(dataType);

        //设置解析完毕的数据模型回调
        this.setCallback(callback);
    }
}
